package com.westcom.healthmate.common.network.http;

import com.westcom.healthmate.common.constants.Constants;
import com.westcom.healthmate.common.exception.ErrorException;
import org.apache.http.*;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.*;

public class HttpUtils
{
    private static final Logger logger = LoggerFactory.getLogger(HttpUtils.class);
    public static Response post(String url,Map<String,Object> headers,HttpEntity entity)throws ErrorException
    {
        Header[] header = convertHeader(headers);
        Response response = null;
        SyncPost httpPost = SyncPost.create();
        try
        {
            HttpResponse res = httpPost.post(url,header,entity);
            response = new Response(res);
        } catch (Exception e)
        {
            e.printStackTrace();
            logger.error("post failed,url:{},header:{},msg:{}",url,header,e.getMessage());
            throw new ErrorException(e);
        }
        return response;
    }
    public static Response get(String url,Map<String,Object> headers) throws ErrorException
    {
        Header[] header = convertHeader(headers);
        Response response;
        try
        {
            SyncGet httpGet = SyncGet.create();
            HttpResponse res = httpGet.get(url,header);
            response = new Response(res);
        } catch (Exception e)
        {
            e.printStackTrace();
            logger.error("get failed,url:{},header:{},msg:{}",url,header,e.getMessage());
            throw new ErrorException(e);
        }
        return response;
    }

    public static Response put(String url,Map<String,Object> headers,HttpEntity entity)throws ErrorException
    {
        Header[] header = convertHeader(headers);
        Response response;
        try
        {
            SyncPut httpPut = SyncPut.create();
            HttpResponse res = httpPut.put(url,header,entity);
            response = new Response(res);
        } catch (Exception e)
        {
            e.printStackTrace();
            logger.error("get failed,url:{},header:{},msg:{}",url,header,e.getMessage());
            throw new ErrorException(e);
        }
        return response;
    }

    public static Response delete(String url,Map<String,Object> headers,HttpEntity entity)throws ErrorException
    {
        Header[] header = convertHeader(headers);
        Response response;
        try
        {
            SyncDelete httpDelete = SyncDelete.create();
            HttpResponse res = httpDelete.delete(url,header,entity);
            response = new Response(res);
        } catch (Exception e)
        {
            e.printStackTrace();
            logger.error("get failed,url:{},header:{},msg:{}",url,header,e.getMessage());
            throw new ErrorException(e);
        }
        return response;
    }
    public static String buildGetUrl(String url,Map<String,Object> param)
    {
        StringBuilder sb = new StringBuilder(url);
        sb.append("?");
        param.keySet().stream().forEach(key->
        {
            sb.append(key).append("=").append(param.get(key)).append("&");
        });
        return sb.toString().substring(0,sb.toString().length()-1);
    }

    public static Header[] convertHeader(Map<String,Object> headers)
    {
        if(null == headers)
        {
            headers = new HashMap<>();
        }
        headers.put(Constants.HTTP_HEADER_NAME_CHARSET,Constants.HTTP_HEADER_VALUE_CHARSET);
        List<Header> hList = null;
        if (null != headers && headers.size() > 0)
        {
            hList = new ArrayList<>();
            Iterator<String> keyI = headers.keySet().iterator();
            while (keyI.hasNext()) {
                String key = keyI.next();
                hList.add(new BasicHeader(key, (String) headers.get(key)));
            }
        } else {
            return null;
        }
        Header[] hArray = null;
        if (!CollectionUtils.isEmpty(hList)) {
            hArray = new Header[hList.size()];
            hArray = hList.toArray(hArray);
        } else
        {
            return null;
        }
        return hArray;
    }
}